package com.fang.algorithm.leecode;

import java.util.HashSet;
import java.util.Set;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。
 * 输入: s = "abcabcbb"
 * 输出: 3
 * 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
 * @date 2022/1/12 2:11 下午
 **/
public class Test02_String {
    public static void main(String[] args) {
        String s = "abcdabcbbss";
        int size = noRepeatSize(s);
        int size1 = test(s);
        System.out.println(size + "," + size1);
    }

    private static int noRepeatSize(String s) {
        Set<Character> set = new HashSet<>();
        int n = s.length();
        int rightPointer = -1, ans = 0;
        for (int i = 0; i < n; i++) {
            if (i != 0) {
                set.remove(s.charAt(i - 1));
            }
            while (rightPointer + 1 < n && !set.contains(s.charAt(rightPointer + 1))) {
                set.add(s.charAt(rightPointer + 1));
                rightPointer++;
            }
            ans = Math.max(ans, rightPointer - i + 1);
        }
        return ans;
    }

    private static int test(String s) {
        Set<Character> set = new HashSet<>();
        int offset = -1, ans = 0, n = s.length();
        for (int i = 0; i < n; i++) {
            while (offset + 1 < n && !set.contains(s.charAt(offset + 1))) {
                set.add(s.charAt(offset + 1));
                offset++;
            }
            ans = Math.max(ans, offset + 1 - i);
        }
        return ans;
    }
}
